package com.djhu.freepartner.web.service.impl;

import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.utils.DateUtils;
import com.djhu.freepartner.utils.GeneralUtils;
import com.djhu.freepartner.web.service.IFileService;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

@Service
@Slf4j
public class LocalFileServiceImpl implements IFileService {

    @Value("${spring.freepartner.static.url}")
    private String image_url;

    @Value("${spring.freepartner.static.path}")
    private String image_path;


    public String getDir(String fileName){
        String today = DateUtils.today();
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR);
        int minite =  calendar.get(Calendar.MINUTE);
        return Joiner.on("/").join(today,hour,minite);
    }

    public String getFileName(String fileName){
        String prefix = GeneralUtils.getUUID().substring(0,5);
        return prefix + "_" + fileName;
    }

    @Override
    public String store(MultipartFile multipartFile) throws ServiceException {

        String fileName = null;
        try {
            fileName = new String(multipartFile.getOriginalFilename().getBytes("GBK"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            fileName = multipartFile.getOriginalFilename();
        }
        log.info("上传图片:size={},name={}",multipartFile.getSize(),fileName);
        String tempDir = getDir(multipartFile.getOriginalFilename());

        //实体机 存放目录
        String dir = image_path + tempDir;
        File rootDir = new File(dir);
        if (!rootDir.exists()){
            try {
                FileUtils.forceMkdir(rootDir);
            } catch (IOException e) {
                log.error("mkdir error",rootDir);
                throw new ServiceException("文件夹创建失败",Status.SERVER_ERROR.getCode());
            }
        }
        //本机文件名
        String tempFile = getFileName(multipartFile.getOriginalFilename());
        String imagePath = rootDir + File.separator +  (tempFile);
        try {
            FileUtils.writeByteArrayToFile(new File(imagePath),multipartFile.getBytes());
            log.info("local file ,local path is {}",imagePath);
        } catch (IOException e) {
            throw new ServiceException(fileName+ "上传失败 " ,Status.FILE_UPLOAD_ERROR.getCode());
        }
        String url = image_url +   tempDir + "/" + tempFile;
        log.info("文件上传成功，ret url is {}",url);
        return url;
    }


}
